package com.moleq.dialog;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.moleq.base.MGposSender;
import com.moleq.base.MoleQBaseDialog;
import com.moleq.device.BasePinPad;
import com.moleq.device.BasePinPad.OnSignatureListener;
import com.moleq.device.printer.Printer;
import com.moleq.device.printer.PrinterBufferRowColection;
import com.moleq.device.printer.TV88MPrinter;
import com.moleq.device.DeviceManager;
import com.moleq.device.IDeviceEvent;
import com.moleq.device.MPaymentRequest;
import com.moleq.device.MPaymentResponse;
import com.moleq.device.PaxPinPad;
import com.moleq.dialog.MessageDialog.OnClickMessageListener;
import com.moleq.enums.PaymentType;
import com.moleq.enums.TransactionType;
import com.moleq.logic.DialogManager;
import com.moleq.logic.MoleQConstants;
import com.moleq.logic.PosPrinter;
import com.moleq.logic.ReceiptManager;
import com.moleq.logic.TransactionManager;
import com.moleq.mgpos.activities.R;
import com.moleq.mgpos.widget.NumberPadForPayment;
import com.moleq.models.FreeFuncRpt;
import com.moleq.models.GlobalInfo;
import com.moleq.models.PosTender;
import com.moleq.models.PrinterSetting;
import com.moleq.models.RoundingSetting;
import com.moleq.models.SaleListItem;
import com.moleq.models.TenderSignature;
import com.moleq.service.ServiceManager;
import com.moleq.util.BigDecmialTool;
import com.moleq.util.MoleQUtil;
import com.moleq.util.RoundUtil;

public class PaymentDialog2 extends MoleQBaseDialog implements IDeviceEvent {

//	private static final int POPUP_MSG_DIALOG_ACTION = 1;

	private InputAuthInfoDialog mInputAuthInfoDlg;
	private Button btnCashPayment;
	private Button btnCreditCardPayment;
	private Button btnDebitCardPayment;
	private Button btnFoodStampPayment;
	private Button btnCheckPayment;
	private Button btnGiftCardPayment;
	private Button btnBack;

	private NumberPadForPayment numberPanel;
	private List<PosTender> mDataItems = new ArrayList<PosTender>();

	private TextView mTextViewDue;
	private TextView mTextViewTotal;
	private TextView mTextViewFs;
	private TextView mTextViewShowFs;
	private TextView mTextViewShowTax;
	private TransactionManager mPaymentMgr;
	private Context mContext;
	private ListView mListView;
	private TenderAdapter mAdapter;
	private DeviceManager mDeviceManager;
	private PaxPinPad posdev;
	private double mCurrentPaid = 0;
	public PosTender mCurrentTender = new PosTender();
	private TextView mTextViewLabelTax;
	private TextView mTextViewLabelDue;
	private TextView mTextViewLabelTotal;
	private PaymentType mCurrentPaymentType;
	private MGposSender mPosSender = null;
	private ProgressDialog mPayingProgress = null;
	 private ConfirmSignatureDialog mConfirmSignatureDialog = null;
	private DeleteCashSelectionDialog mDeleteCashSelectionDialog;
	// private SignatureMessageDialog mSignatureMessageDialog = null;
	// private RoundingSetting mRoundingSetting = null;
	private RoundingSetting roundSetup = null;
	private double roundedValue = 0;
	private MPaymentResponse mPaymentResponse = null;
	private MPaymentRequest mPaymenyRequest = null;
	

	public int tenderIndex = -1;
	private Button btnDeleteCash;
	

	class TenderAdapter extends BaseAdapter {

		private Context mContext;

		public final class ListItemView {
			public TextView tvTenderDesc;
			public TextView tvPaymentDesc;
			public TextView tvPaid;
//			public ImageButton ibtn_delete_tender;
		}

		public TenderAdapter(Context context) {
			mContext = context;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mDataItems.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return mDataItems.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ListItemView liv = null;
//			if (convertView == null) {
				liv = new ListItemView();

				convertView = LayoutInflater.from(mContext).inflate(R.layout.tender_item2, null);
				liv.tvTenderDesc = (TextView) convertView.findViewById(R.id.textViewTenderDesc);
				liv.tvPaymentDesc = (TextView) convertView.findViewById(R.id.textViewTenderPaymentDesc);
				liv.tvPaid = (TextView) convertView.findViewById(R.id.textViewTenderPaid);
//				liv.ibtn_delete_tender = (ImageButton) convertView.findViewById(R.id.ibtn_delete_tender);
//				liv.ibtn_delete_tender.setTag(position);
				mDataItems.get(position).index = position;
//				liv.ibtn_delete_tender.setOnClickListener(mOnTenderClickListener);
				
				convertView.setTag(liv);
//			} else {
//				liv = (ListItemView) convertView.getTag();
//			}

			liv.tvTenderDesc.setText("Tender " + String.valueOf(position + 1));
			liv.tvPaymentDesc.setText(mDataItems.get(position).paymentType.getText());
			liv.tvPaid.setText(MoleQUtil.fixPrintPrice(mDataItems.get(position).getPt_tender()));
//			if (mDataItems.get(position).paymentType == PaymentType.CASH) {
//				liv.ibtn_delete_tender.setVisibility(View.VISIBLE);
//			}else{
//				liv.ibtn_delete_tender.setVisibility(View.INVISIBLE);
//			}
			return convertView;
		}

	}

	public PaymentDialog2(Context context) {
		super(context, context);
		mContext = context;
		// TODO Auto-generated constructor stub
	}

	public PaymentDialog2(Context context, int theme) {
		super(context, theme, context);
		mContext = context;
		// TODO Auto-generated constructor stub
	}

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		this.setContentView(R.layout.dialog_payment);

		mTextViewDue = (TextView) findViewById(R.id.textViewPaymentSelectionDue);
		mTextViewTotal = (TextView) findViewById(R.id.textViewPaymentSelectionTotal);
		mTextViewFs = (TextView) findViewById(R.id.tvLabelFS);
		mTextViewFs.setText(String.format(this.mContext.getResources().getString(R.string.label_foodstamp), GlobalInfo.getInstance().CurrencySymbol));

		mTextViewLabelTax = (TextView) findViewById(R.id.tvLabelTax);
		mTextViewLabelTax.setText(String.format(this.mContext.getResources().getString(R.string.label_tax), GlobalInfo.getInstance().CurrencySymbol));

		mTextViewLabelDue = (TextView) findViewById(R.id.tvLabelDue);
		mTextViewLabelDue.setText(String.format(this.mContext.getResources().getString(R.string.label_due), GlobalInfo.getInstance().CurrencySymbol));

		mTextViewLabelTotal = (TextView) findViewById(R.id.tvLabelTotal);
		mTextViewLabelTotal.setText(String.format(this.mContext.getResources().getString(R.string.label_total), GlobalInfo.getInstance().CurrencySymbol));

		mTextViewShowFs = (TextView) findViewById(R.id.textViewPaymentSelectionfs);
		mTextViewShowTax = (TextView) findViewById(R.id.textViewPaymentSelectiontax);

		btnCashPayment = (Button) findViewById(R.id.buttonCashPayment);
		btnCashPayment.setOnClickListener(mOnClickListener);

		btnCreditCardPayment = (Button) findViewById(R.id.buttonCreditCardPayment);
		btnCreditCardPayment.setOnClickListener(mOnClickListener);

		btnDebitCardPayment = (Button) findViewById(R.id.buttonDebitCardPayment);
		btnDebitCardPayment.setOnClickListener(mOnClickListener);

		btnFoodStampPayment = (Button) findViewById(R.id.buttonFoodstampPayment);
		btnFoodStampPayment.setOnClickListener(mOnClickListener);

		btnCheckPayment = (Button) findViewById(R.id.buttonCheckPayment);
		btnCheckPayment.setOnClickListener(mOnClickListener);

		btnGiftCardPayment = (Button) findViewById(R.id.buttonGiftCardPayment);
		btnGiftCardPayment.setOnClickListener(mOnClickListener);

		btnBack = (Button) findViewById(R.id.buttonPaymentSelectionClose);
		btnBack.setOnClickListener(mOnClickListener);

		btnDeleteCash = (Button) findViewById(R.id.buttonDeleteCashPayment);
		btnDeleteCash.setOnClickListener(mOnClickListener);
		
		
		numberPanel = (NumberPadForPayment) findViewById(R.id.numberPadPayment);
		numberPanel.disableKey(R.id.numberPadKeyEnter);

		mListView = (ListView) findViewById(R.id.listViewCheckoutTenderList);
		mAdapter = new TenderAdapter(mContext);
		mListView.setAdapter(mAdapter);

		this.setCancelable(false);
		mPayingProgress = DialogManager.createProgressDialog(mContext);
		roundSetup = GlobalInfo.getInstance().mRoundingSetting;
		
		mConfirmSignatureDialog = new ConfirmSignatureDialog(mContext,this);
		
	}

	private OnSignatureListener mOnSignatureListener = new OnSignatureListener() {

		

		@Override
		public void onDoSignature(int what, Object response) {
			if (!posdev.isUploadSignatureCapture) {
				posdev.getSignature();
			}else{
				checkout();
				mPayingProgress.dismiss();
			}
			
		}

		@Override
		public void onSignatureTimeOut() {

		}

		@Override
		public void onGetSignature(int what, Object response) {
			MPaymentResponse mresponse1 = (MPaymentResponse) response;

			
			mPayingProgress.dismiss();
			mConfirmSignatureDialog.show(mresponse1.ResultSignature);

//			MessageBox.show(mContext, "Save signature succeed. \n" + mresponse1.ResultCode + "\n"+ mresponse1.ResultTxt +"\n" +mresponse1.ResultSignature );
		}

		@Override
		public void onError(int what, Object response) {
			MPaymentResponse mresponse = null;
			switch (what) {
			case BasePinPad.DOSIGNATURE_TIMEOUT:
			case BasePinPad.GETSIGNATURE_TIMEOUT:
				MessageBox.show(mContext, mContext.getResources().getString(R.string.msg_signature_agn_prt), mAgainSignatureListener, MessageDialog.MESSAGE_BOX_YES_NO);
				mPayingProgress.dismiss();
				break;

			case BasePinPad.DOSIGNATURE_FAILED:
				MessageBox.show(mContext, mContext.getResources().getString(R.string.msg_signature_agn_prt), mAgainSignatureListener, MessageDialog.MESSAGE_BOX_YES_NO);
				mPayingProgress.dismiss();
				break;

			case BasePinPad.GETSIGNATURE_FAILED:
				
				mresponse = (MPaymentResponse) response;
				if (posdev.isUploadSignatureCapture) {
					MessageBox.show(mContext, "Get signature failed. \n" + mresponse.ResultCode + "\n"+ mresponse.ResultTxt );
					mPayingProgress.dismiss();
					checkout();
				}else{
					mPaymenyRequest.PayType = mCurrentTender.paymentType;
					mPaymenyRequest.HostCode = mCurrentTender.HostCode;
					posdev.doSignature();
				}
				
				break;

			}
		}

	};
	

	public void show() {
		super.show();

		numberPanel.reset();
		numberPanel.requestFocusFromTouch();

		mInputAuthInfoDlg = new InputAuthInfoDialog(mContext, this);
		mPayingProgress = DialogManager.createProgressDialog(mContext);
		mDeleteCashSelectionDialog = new DeleteCashSelectionDialog(mContext,this);
		mPosSender = MGposSender.getInstance();
		mPaymentMgr = TransactionManager.getInstance();
		mDeviceManager = DeviceManager.getInstance();
		mDeviceManager.disableAllScanner();

		if (mDeviceManager.pinPadIsReady) {
			mPaymenyRequest = new MPaymentRequest();
			mPaymentResponse = new MPaymentResponse();
			posdev = (PaxPinPad) mDeviceManager.pinPad;
			posdev.setCallbackEvent(this);
			posdev.setOnSignatureListener(mOnSignatureListener);
			posdev.bindPaymentRequest(mPaymenyRequest);
			posdev.bindPaymentResponse(mPaymentResponse);
		}

		// mDataItems = mPaymentMgr.getTenderList();
		mDataItems = mPaymentMgr.tenderList;
		mAdapter.notifyDataSetChanged();

		mTextViewShowFs.setText(MoleQUtil.fixNumber(mPaymentMgr.getDueFoodstamp()));
		mTextViewShowTax.setText(MoleQUtil.fixNumber(mPaymentMgr.getTotalTax()));

		mTextViewTotal.setText(MoleQUtil.fixNumber(mPaymentMgr.getAmountPayable()));
		mTextViewDue.setText(MoleQUtil.fixNumber(mPaymentMgr.getDue()));
		mDeviceManager.screen.displayLine("Total: " + MoleQUtil.fixPriceForScreen(mPaymentMgr.getAmountPayable()) + "\n Due: " + MoleQUtil.fixPriceForScreen(mPaymentMgr.getDue()));
		mPosSender.sendRed(MoleQUtil.getSenderString("END"));
		if (mPaymentMgr.getTotalTax() > 0) {
			mPosSender.sendRed("Tax " + mTextViewShowTax.getText());
		}
		if (mPaymentMgr.getDueFoodstamp() > 0) {
			mPosSender.sendRed("FOODSTAMP " + mTextViewShowFs.getText());
		}
		mPosSender.sendRed("TRANSACTION TOTAL " + GlobalInfo.getInstance().CurrencySign + MoleQUtil.fixNumber(mPaymentMgr.getAmountPayable()));

	}
	


	private Button.OnClickListener mOnClickListener = new Button.OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.buttonPaymentSelectionClose:
				mPosSender.send(MoleQUtil.getSenderString("BACK"));
				mDeviceManager.enableAllScanner();
				dismiss();
				break;
			case R.id.buttonCashPayment:
				GlobalInfo.getInstance().CurrentFreeFuncID = FreeFuncRpt.FF_CASH;
				pay(PaymentType.CASH);

				break;
			case R.id.buttonCreditCardPayment:
				GlobalInfo.getInstance().CurrentFreeFuncID = FreeFuncRpt.FF_CREDIT_CARD;
				pay(PaymentType.CREDIT_CARD);

				break;
			case R.id.buttonDebitCardPayment:
				GlobalInfo.getInstance().CurrentFreeFuncID = FreeFuncRpt.FF_DEBIT_CARD;
				pay(PaymentType.DEBIT_CARD);
				break;
			case R.id.buttonFoodstampPayment:
				GlobalInfo.getInstance().CurrentFreeFuncID = FreeFuncRpt.FF_FOOD_STAMP;
				pay(PaymentType.FOOD_STAMP);
				break;
			case R.id.buttonCheckPayment:
				GlobalInfo.getInstance().CurrentFreeFuncID = FreeFuncRpt.FF_CHECK;
				pay(PaymentType.CHECK);
				break;
			case R.id.buttonGiftCardPayment:
				GlobalInfo.getInstance().CurrentFreeFuncID = FreeFuncRpt.FF_GIFT_CARD;
				pay(PaymentType.GIFT_CARD);
				break;
			case R.id.buttonDeleteCashPayment:
				if (haveCashPayment()) {
					mDeleteCashSelectionDialog.show();
				}
				break;
			}

		}

	};

	private String getInputPayAmount() {
		String sInputPaid = numberPanel.getBuffer();
		String result = "";
		if (sInputPaid.equals("")) {
			if (mCurrentPaymentType == PaymentType.FOOD_STAMP) {
				numberPanel.setBuffer(MoleQUtil.fixNumber(mPaymentMgr.getDueFoodstamp()));
				return result;
			}
			numberPanel.setBuffer(MoleQUtil.fixNumber(mPaymentMgr.getDue()));
			return result;
		} else if (sInputPaid.equals(".")) {
			return result;
		} else {
			sInputPaid = sInputPaid.replace(",", "");
			BigDecimal b1 = new BigDecimal(sInputPaid);
			double dInputPaid = b1.doubleValue();

			if (sInputPaid.contains(".")) {
				sInputPaid = String.format("%.0f", dInputPaid * 100);
			} else {
				dInputPaid /= 100;
				sInputPaid = String.format("%.0f", dInputPaid * 100);
			}

			if (Double.valueOf(dInputPaid) >= 99999) {
				MessageBox.show(mContext, "The amount is too large.");
				return result;
			}

			return sInputPaid;
		}
	}

	private void pay(PaymentType paymentType) {
		mCurrentPaymentType = paymentType;
		String strPaid = getInputPayAmount();

		if (strPaid.equals(""))
			return;

		mCurrentPaid = Double.valueOf(strPaid);
		mCurrentPaid /= 100;

		if (mCurrentPaid > 0 || (GlobalInfo.getInstance().isZeroBaln && mCurrentPaid == 0 && mPaymentMgr.getDue() == 0)) {

			double ddd = mPaymentMgr.getDue();
			mCurrentTender = new PosTender();
			mCurrentTender.setPt_seq_no(ServiceManager.getInstance().mPoslineTenderService.getMaxSeqNo() + 1);
			mCurrentTender.setPt_id(ServiceManager.getInstance().mPoslineTenderService.getMaxNo() + 1);
			mCurrentTender.paymentType = mCurrentPaymentType;
			mCurrentTender.setPt_tender(mCurrentPaid);
			mCurrentTender.setPt_trn_no(mPaymentMgr.TransactionNo);
			String mCurrentPaidDisplay = MoleQUtil.fixPriceForScreen(mCurrentPaid);

			switch (paymentType) {
			case CASH:
				mPosSender.send("Tender Cash " + mCurrentPaidDisplay);
				double due = mPaymentMgr.getDue();
				if (mCurrentPaid >= due && roundSetup != null) {
					double downValue = roundSetup.getRs_down_value();
					double upValue = roundSetup.getRs_up_value();
					double toValue = roundSetup.getRs_to_value();
					roundedValue = RoundUtil.toRound(due, downValue, upValue, toValue);
					if (BigDecmialTool.round(roundedValue, 2) != BigDecmialTool.round(due, 2)) {
						if (roundSetup.getOptional()) {
							MessageBox.show(mContext, "Do you want to rounding?", mRoundingListener, MessageDialog.MESSAGE_BOX_YES_NO);
						} else {
							roundCashPay();
						}
						return;
					}

				}

				ConfirmTender();
				checkout();

				// pay(mCurrentPaid,paymentType);
				break;
			case CHECK:
				// mInputAuthInfoDlg = new InputAuthInfoDialog(mContext,this);
				// if(!mInputAuthInfoDlg.isShowing()) mInputAuthInfoDlg.show();
				if (mInputAuthInfoDlg == null || mInputAuthInfoDlg.isShowing())
					return;

				mInputAuthInfoDlg.show();
				mPosSender.send("Tender Check " + mCurrentPaidDisplay);
				break;

			case CREDIT_CARD:
			
				if (mCurrentPaid > ddd)
					return;

				if (mDeviceManager.pinPadIsReady && posdev.isEnable() && posdev.isConnected()) {

					mDeviceManager.screen.displayLine("Processing.... ");
					mPayingProgress.setMessage("Processing.... ");
					mPayingProgress.show();

					//mPaymenyRequest = new MPaymentRequest();
					mPaymenyRequest.appDataFolder = GlobalInfo.getInstance().appDataFolder;
					mPaymenyRequest.refNum = mPaymentMgr.getRefNum();
					mPaymenyRequest.TransType = mPaymentMgr.TransType;
					mPaymenyRequest.PayType = paymentType;
					mPaymenyRequest.paymentAmount = strPaid;
					
					posdev.reset();
					posdev.SignMinAmt = GlobalInfo.getInstance().sigMinValue;
					posdev.PayAmt = mCurrentTender.getPt_tender();
					posdev.ProcessPayment();

				} else {
					if (mInputAuthInfoDlg == null || mInputAuthInfoDlg.isShowing())
						return;

					mInputAuthInfoDlg.show();
				}
				mPosSender.send("Tender Credit Card " + mCurrentPaidDisplay);
				break;
			case DEBIT_CARD:

				if (mCurrentPaid > ddd)
					return;

				if (mDeviceManager.pinPadIsReady && posdev.isEnable() && posdev.isConnected()) {

					mDeviceManager.setDisplayMessage("Processing.... ");
					mPayingProgress.setMessage("Processing.... ");
					mPayingProgress.show();
					
//					mPaymenyRequest = new MPaymentRequest();
					mPaymenyRequest.appDataFolder = GlobalInfo.getInstance().appDataFolder;
					mPaymenyRequest.refNum = mPaymentMgr.getRefNum();
					mPaymenyRequest.TransType = mPaymentMgr.TransType;
					mPaymenyRequest.PayType = paymentType;
					mPaymenyRequest.paymentAmount = strPaid;
					
					posdev.reset();
					posdev.ProcessPayment();

				} else {
					if (mInputAuthInfoDlg == null || mInputAuthInfoDlg.isShowing())
						return;

					mInputAuthInfoDlg.show();
				}
				// pay(mCurrentPaid,paymentType);
				mPosSender.send("Tender Debit Card " + mCurrentPaidDisplay);
				break;

			case FOOD_STAMP:
				if (mCurrentPaid > mPaymentMgr.getDueFoodstamp()) {
					MessageBox.show(mContext, mContext.getResources().getString(R.string.msg_not_pay_fs));
					return;
				}

				if (!mPaymentMgr.canPayFoodstamp()) {
					MessageBox.show(mContext, "Cannot pay with food stamp.");
					return;
				}

				if (mDeviceManager.pinPadIsReady && posdev.isEnable() && posdev.isConnected()) {

					mDeviceManager.screen.displayLine("Processing.... ");
					mPayingProgress.setMessage("Processing.... ");
					mPayingProgress.show();

					mPaymenyRequest.appDataFolder = GlobalInfo.getInstance().appDataFolder;
					mPaymenyRequest.refNum = mPaymentMgr.getRefNum();
					mPaymenyRequest.TransType = mPaymentMgr.TransType;
					mPaymenyRequest.PayType = paymentType;
					mPaymenyRequest.paymentAmount = strPaid;

					posdev.reset();
					posdev.ProcessPayment();
				} else {

					if (mInputAuthInfoDlg == null || mInputAuthInfoDlg.isShowing())
						return;

					mInputAuthInfoDlg.show();
				}
				mPosSender.send("Tender Food Stamp " + mCurrentPaidDisplay);
				break;
			case EBT_CASH:
				//
				// pay(mCurrentPaid,paymentType);
				mPosSender.send("Tender EBT CASH " + mCurrentPaidDisplay);
				ConfirmTender();
				checkout();
				break;

			case GIFT_CARD:
				if (mCurrentPaid > ddd)
					return;

				if (mDeviceManager.pinPadIsReady && posdev.isEnable() && posdev.isConnected()) {

					mDeviceManager.screen.displayLine("Processing.... ");
					mPayingProgress.setMessage("Processing.... ");
					mPayingProgress.show();

					mPaymenyRequest.appDataFolder = GlobalInfo.getInstance().appDataFolder;
					mPaymenyRequest.refNum = mPaymentMgr.getRefNum();
					mPaymenyRequest.TransType = mPaymentMgr.TransType;
					mPaymenyRequest.PayType = paymentType;
					mPaymenyRequest.paymentAmount = strPaid;

					posdev.reset();
					posdev.ProcessPayment();

				} else {
					if (mInputAuthInfoDlg == null || mInputAuthInfoDlg.isShowing())
						return;

					mInputAuthInfoDlg.show();
				}
				mPosSender.send("Tender Gift Card " + mCurrentPaidDisplay);
				// pay(paid,paymentType);
				break;
			case GIFT_CERTIFICATE:
				//
				// pay(mCurrentPaid,mCurrentPaymentType);
				ConfirmTender();
				checkout();
				break;
			case STORE_CREDIT:
				//
				// pay(mCurrentPaid,paymentType);
				ConfirmTender();
				checkout();
				break;
			case VOICE_AUTH:
				//
				// pay(mCurrentPaid,paymentType);
				ConfirmTender();
				checkout();
				break;
			case VOUCHER:
				//
				// pay(mCurrentPaid,paymentType);
				ConfirmTender();
				checkout();
				break;
			}

		}

	}

	public void ConfirmTender() {

		if (mCurrentTender != null && mCurrentTender.paymentType != null && mCurrentTender.getPt_seq_no() > 0) {
			mCurrentTender.setPt_function(MoleQUtil.getPaymentTypeID(mCurrentTender.paymentType));
			mPaymentMgr.addTender(mCurrentTender);
			ServiceManager.getInstance().mPoslineTenderService.Insert(mCurrentTender);

			// foodstampPrice Feng
			if (mCurrentTender.paymentType == PaymentType.FOOD_STAMP)
				mPaymentMgr.setFoodStampPrice(mCurrentPaid);
		}

		refreshDisplay();

	}

	public void checkout() {

		if (mPaymentMgr.getDue() <= 0) {
			mPaymentMgr.mTransType = "Y";
			mPaymentMgr.UpdatePosTrn();

			for (int i = 0; i < mPaymentMgr.tenderList.size(); i++) {
				PosTender tender = mPaymentMgr.tenderList.get(i);
				ServiceManager.getInstance().mPosTenderService.Insert(new PosTender(GlobalInfo.getInstance().storeNo, 
						GlobalInfo.getInstance().stationNo, 
						MoleQUtil.getNow(), tender.getPt_seq_no(), "N", 
						tender.getPt_function(), 
						tender.getPt_due(), tender.getPt_tender(), 
						tender.getPt_change(), tender.getPt_ref_no(), 
						null, tender.getPt_card_type(), 
						tender.getPt_card_no(), 
						tender.getPt_Auth(),tender.getHostCode(),tender.getPt_trn_no()));
			}
			// save free function

			if (mPaymentMgr.mTaxExempat >= 0) {
				GlobalInfo.getInstance().useFuntionsList.add(GlobalInfo.getInstance().CurrentFreeFuncID);
				mPaymentMgr.SaveFreeFuncRpt(FreeFuncRpt.FF_TAX_EXEMPT, 1, mPaymentMgr.getCurrentTax() * (-1));
			}
			if (mPaymentMgr.TransType == TransactionType.WIC) {
				mPaymentMgr.SaveFreeFuncRpt(FreeFuncRpt.FF_WIC, 1, mPaymentMgr.CVVWicPrice);
			} else if (mPaymentMgr.TransType == TransactionType.CVV) {
				mPaymentMgr.SaveFreeFuncRpt(FreeFuncRpt.FF_CVV, 1, mPaymentMgr.CVVWicPrice);
			}

			// save ej
			String contents = "";
			String receiptContent = "";
			String serviceContent = "";
			if (mPaymentMgr.isNeedSignature()) {
				ArrayList<PosTender> tendrs = mPaymentMgr.getTendersByPaymentType(PaymentType.CREDIT_CARD);
				for (int i = 0; i < tendrs.size(); i++) {
					if (tendrs.get(i).isNeedPrint && tendrs.get(i).getPt_tender() >= GlobalInfo.getInstance().sigMinValue) {
						PrinterBufferRowColection printBuffer = ReceiptManager.getSignature(mPaymentMgr.TransactionNo, mPaymentMgr.dDoneDate, GlobalInfo.getInstance().cashier, tendrs.get(i), mPaymentMgr.isReprint);
						contents += printBuffer.toReceipt();
					}
				}
			}
			PrinterBufferRowColection printBuffer2 = ReceiptManager.getSaleReceipt(GlobalInfo.getInstance().cashier, mPaymentMgr);
			receiptContent = printBuffer2.toReceipt();
			//print service item
			if (mPaymentMgr.haveServiceItem() && GlobalInfo.getInstance().isPrintServiceItem
					&& !MoleQUtil.getTransType(mPaymentMgr.TransType).equals("R")) {
				List<SaleListItem> listItem = new ArrayList<SaleListItem>();
				
				//print local
				listItem = mPaymentMgr.getServiceItemAllList();
				PrinterBufferRowColection printBuffer3 = ReceiptManager.getServiceTicketLocalReceipt(GlobalInfo.getInstance().cashier, mPaymentMgr, listItem);
				serviceContent += printBuffer3.toReceipt();
				
				//print none
				listItem = mPaymentMgr.getServiceItemListByID(0);
				if (listItem.size() > 0) {
					PrinterBufferRowColection printBuffer4 = ReceiptManager.getServiceItemReceipt(GlobalInfo.getInstance().cashier, mPaymentMgr, listItem);
					serviceContent += printBuffer4.toReceipt();
				}
				
				//print not connect
				List<PrinterSetting> listPrinter = ServiceManager.getInstance().mPrinterSettingService.FindAll();
				for (int i = 0; i < listPrinter.size(); i++) {
					listItem = mPaymentMgr.getServiceItemListByID(listPrinter.get(i).getPs_id());
					if (listItem.size() == 0) continue;
					
					Printer svrPrinter = DeviceManager.getInstance().ServiceTicketPrinters.get(listPrinter.get(i).getPs_id());
					svrPrinter.open();
					if (svrPrinter.isEnable()) {
						svrPrinter.close();
					}else {
						PrinterBufferRowColection printBuffer5 = ReceiptManager.getServiceItemReceipt(GlobalInfo.getInstance().cashier, mPaymentMgr, listItem);
						serviceContent += printBuffer5.toReceipt();
						svrPrinter.close();
					}
				}
			}
			mPaymentMgr.SaveEJ(contents + receiptContent + serviceContent);
			mPaymentMgr.exportInvFile();

			// check out
			onCloseWithReturn(MoleQConstants.PAYMENT_CHECK_OUT, "");
			// onResultActiveOption(FunctionOption.PAYMENT_CHECK_OUT);
			// onResultActiveOption(FunctionOption.OPEN_CASH_DRAWER);
			// onResultActiveOption(FunctionOption.PRINT_RECEIPT);
			dismiss();
		} else {
			refreshDisplay();
		}
	}
	
	public boolean haveCashPayment(){
		
		for (int i = 0; i < mPaymentMgr.tenderList.size(); i++) {
			if (mPaymentMgr.tenderList.get(i).paymentType == PaymentType.CASH) {
				return true;
			}
		}
		return false;
	}

	public void roundCashPay() {

		mPaymentMgr.Rounding_flag = "1";
		ServiceManager.getInstance().mPosTrnsService.UpdateRoundFlag("1", mPaymentMgr.TransactionNo);
		if (roundSetup != null) {
			double due = mPaymentMgr.getDue(), tender = mCurrentPaid;

			String roundInfo = " Original Price: " + MoleQUtil.fixPriceForScreen(due) + "\n Round to: " + MoleQUtil.fixPriceForScreen(roundedValue);
			// if (roundedValue != mCurrentPaid) {
			mCurrentTender.afterRoundingValue = roundedValue;
			mCurrentTender.beforRoundingValue = due;
			if (mCurrentTender.isRoundup()) {
				if (mCurrentPaid <= roundedValue) {
					tender = roundedValue;
				}
			} else {
				if (mCurrentPaid > roundedValue) {
					if (mCurrentPaid == due) {
						tender = roundedValue;
					} else {
						tender = mCurrentPaid;
					}
				}
			}

			// if (roundedValue < mCurrentPaid) {
			// tender = mCurrentPaid;\
			// }
			mCurrentTender.setPt_tender(tender);
			mPaymentMgr.Rounding = BigDecmialTool.sub(roundedValue, due);
			MessageDialog messagebox = new MessageDialog(mContext);
			messagebox.show();
			messagebox.setStyle(MessageDialog.MESSAGE_BOX_OK);
			messagebox.setOnClickMessageListener(mRoundpaidistener);
			messagebox.setMessage(roundInfo);
			ServiceManager.getInstance().mPosTrnsService.UpdateRounding(mPaymentMgr.Rounding, mPaymentMgr.TransactionNo);
			// }
		}
	}

	private OnClickMessageListener mDupTranListener = new OnClickMessageListener() {

		@Override
		public void onClickYes() {
			posdev.isForce = true;
			pay(mCurrentTender.paymentType);
		}

		@Override
		public void onClickOK() {

		}

		@Override
		public void onClickNo() {
			// posdev.isForce = false;
			// pay(mCurrentTender.paymentType);

		}
	};

	private OnClickMessageListener mRoundingListener = new OnClickMessageListener() {

		@Override
		public void onClickOK() {

		}

		@Override
		public void onClickYes() {
			// TODO Auto-generated method stub
			roundCashPay();
		}

		@Override
		public void onClickNo() {
			ConfirmTender();
			checkout();
		}
	};

	private OnClickMessageListener mRoundpaidistener = new OnClickMessageListener() {

		@Override
		public void onClickYes() {
		}

		@Override
		public void onClickNo() {
		}

		@Override
		public void onClickOK() {
			ConfirmTender();
			checkout();
		}

	};

	public void refreshDisplay() {
		numberPanel.setBuffer("");
		mAdapter.notifyDataSetChanged();
		mTextViewTotal.setText(MoleQUtil.fixNumber(mPaymentMgr.getAmountPayable()));
		mTextViewDue.setText(MoleQUtil.fixNumber(mPaymentMgr.getDue()));
		mTextViewShowTax.setText(MoleQUtil.fixNumber(mPaymentMgr.getTotalTax()));
		mTextViewShowFs.setText(MoleQUtil.fixNumber(mPaymentMgr.getDueFoodstamp()));
		if (mCurrentTender.paymentType != null) {
			mDeviceManager.screen.displayLine("Tender\n" + mCurrentTender.paymentType.getText() + ":" + MoleQUtil.fixPriceForScreen(mCurrentTender.getPt_tender()));
		}
	}

	private OnClickMessageListener mAgainSignatureListener = new OnClickMessageListener() {

		@Override
		public void onClickYes() {

			mPaymenyRequest.PayType = mCurrentTender.paymentType;
			mPaymenyRequest.HostCode = mCurrentTender.HostCode;
			posdev.doSignature();

			String showMsg = mContext.getResources().getString(R.string.msg_wait_signature);
			mDeviceManager.screen.displayLine(showMsg);
			mPayingProgress.setMessage(showMsg);
			mPayingProgress.show();

		}

		@Override
		public void onClickOK() {

		}

		@Override
		public void onClickNo() {

//			printSignaturePaper(mCurrentTender);
			mCurrentTender.setNeedPrint(true);
			checkout();

		}
	};
	
	@Override
	public void onErrorEvent(String res) {

	}

	@Override
	public void onScannerEvent(String res) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onWeightEvent(int res) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTimeOutEvent() {
		// String flStr = "Time Out";
		// Message msg = new Message();
		// msg.what = POPUP_MSG_DIALOG_ACTION;
		// msg.obj = flStr;
		// mHandler.sendMessage(msg);

		mPayingProgress.dismiss();

		MessageBox.show(mContext, "Time Out");
	}

	@Override
	public void onDataEvent(Object obj) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onEventResponse(int what, Object obj) {

		switch (what) {
		case BasePinPad.PAYMENT_FAILED:
		case BasePinPad.PAYMENT_SUCCEED:
			

			String resutType = mPaymentResponse.ResultType;
			if (resutType.equals(BasePinPad.RESULT_OK)) {

				setTender(mPaymentResponse);
				ConfirmTender();
				
				switch (posdev.SignStatusNum) {
				case -1:
					if (mCurrentTender.paymentType.equals(PaymentType.CREDIT_CARD) 
							&& mCurrentTender.getPt_tender() >= GlobalInfo.getInstance().sigMinValue) {

							if (  posdev.isSignatureCapture) {
								mPaymenyRequest.PayType = mCurrentTender.paymentType;
								mPaymenyRequest.HostCode = mCurrentTender.HostCode;
								posdev.doSignature();

								mPayingProgress.dismiss();
								mPayingProgress.setMessage(mContext.getResources().getString(R.string.msg_wait_signature));
								mPayingProgress.show();

							} else {
//								printSignaturePaper(mCurrentTender);
								mCurrentTender.setNeedPrint(true);
								checkout();
								mPayingProgress.dismiss();
							}
					} else {
						checkout();
						mPayingProgress.dismiss();
					}
					break;
				case 1:
					mPaymenyRequest.PayType = mCurrentTender.paymentType;
					mPaymenyRequest.HostCode =mCurrentTender.HostCode;
					posdev.getSignature();
					break;

				default:
//					printSignaturePaper(mCurrentTender);
					mCurrentTender.setNeedPrint(true);
					checkout();
					mPayingProgress.dismiss();
					break;
				}
				
				
			} else if (resutType.equals(BasePinPad.RESULT_TIMEOUT)) {
				mDeviceManager.screen.displayLine("Time out");
				MessageBox.show(mContext, "Time out");
				mPayingProgress.dismiss();
			} else if (resutType.equals(BasePinPad.RESULT_TERMINAL_ERROR)) {
				mDeviceManager.screen.displayLine("terminal error.");
				MessageBox.show(mContext, "terminal error.");
				mPayingProgress.dismiss();
			} else if (resutType.equals(BasePinPad.RESULT_COMM_ERROR)) {
				mDeviceManager.screen.displayLine("Comm error.");
				MessageBox.show(mContext, "Comm error.");
				mPayingProgress.dismiss();
			} else if (resutType.equals(BasePinPad.RESULT_DECLINE)) {
				mDeviceManager.screen.displayLine("DECLINE");
				MessageBox.show(mContext, "DECLINE");
				mPayingProgress.dismiss();
			} else if (resutType.equals(BasePinPad.RESULT_DUPLICATE_TRANSACTION)) {
				mDeviceManager.screen.displayLine("DUPLICATE_TRANSACTION");
				MessageBox.show(mContext, mContext.getResources().getString(R.string.msg_dup_trans), mDupTranListener, MessageDialog.MESSAGE_BOX_YES_NO);
				mPayingProgress.dismiss();
			} else if (resutType.equals(BasePinPad.RESULT_ABORTED)) {
				mDeviceManager.screen.displayLine("ABORTED");
				MessageBox.show(mContext, "ABORTED");
				mPayingProgress.dismiss();

			} else if (resutType.equals(BasePinPad.RESULT_TRACK_INVALID) || mPaymentResponse.ResultType.equals(BasePinPad.RESULT_SWIPE_ERROR)) {
				mDeviceManager.screen.displayLine("Track invalid or swipe card error.");
				MessageBox.show(mContext, "Track invalid or swipe card error.");
				mPayingProgress.dismiss();
			} else {
				MessageBox.show(mContext, mPaymentResponse.ResultCode + "/n" + mPaymentResponse.ResultTxt);
				mPayingProgress.dismiss();

			}
			break;

		}

	}

	private void setTender(MPaymentResponse response) {

		String cardNo = response.BogusAccountNum;
		if (cardNo != null && !cardNo.equals("")) {
			mCurrentTender.setPt_card_no("xxxxxxxxxxxx" + response.BogusAccountNum);
		}

		// mCurrentTender.ResultCode = response.ResultCode;
		// mCurrentTender.ResultTxt = response.ResultTxt;
		mCurrentTender.setPt_Auth(response.AuthCode);
		// mCurrentTender.ApprovedAmount = response.ApprovedAmount;
		// mCurrentTender.AvsResponse = response.AvsResponse;
		// mCurrentTender.BogusAccountNum = response.BogusAccountNum;
		mCurrentTender.setPt_card_type(response.CardType);
		// mCurrentTender.CvResponse = response.CvResponse;
		mCurrentTender.HostCode = response.HostCode;
		// mCurrentTender.HostResponse = response.HostResponse;
		// mCurrentTender.Message = response.Message;
		mCurrentTender.setPt_ref_no(response.RefNum);
		// mCurrentTender.RemainingBalance = response.RemainingBalance;
		// mCurrentTender.RequestedAmount = response.RequestedAmount;
		// mCurrentTender.Timestamp = response.Timestamp;
		// mCurrentTender.ExtDAta = response.ExtData;

	}

	@Override
	public void onReturnValue(int what, Object obj) {

		switch (what) {
		case DIALOG_INPUT_CHECK_INFO:

			String returnAuth = obj.toString();
			if (returnAuth != null && !returnAuth.equals("")) {
				// pay(mCurrentPaid,mCurrentPaymentType);
				mCurrentTender.setPt_Auth(obj.toString());
				ConfirmTender();
				checkout();
			}
			break;
			
		case MoleQConstants.ON_CLICK_CONFIRM_SIGNATURE:
			String strSign = obj.toString();
			
			if (globalSetting.isSaveSig) {
				TenderSignature ts = new TenderSignature();
				ts.setTs_tender_id(mCurrentTender.getPt_seq_no());
				ts.setTs_signature_value(strSign);
				ts.setTs_trn_no(mCurrentTender.getPt_trn_no());
				ServiceManager.getInstance().mTenderSignatureService.Insert(ts);
				//MessageBox.show(mContext, "Save signature succeed. \n" + strSign);
			}
			mPayingProgress.dismiss();
			checkout();
			break;
		case MoleQConstants.ON_CLICK_REGET_SIGNATURE:
			mPayingProgress.show();
			
			mPaymenyRequest.PayType = mCurrentTender.paymentType;
			mPaymenyRequest.HostCode = mCurrentTender.HostCode;
			posdev.doSignature();
			
			break;
		case R.id.btn_dialog_delete:
			PosTender tempTender = (PosTender)obj;
			if (tempTender != null) {
				ServiceManager.getInstance().mPoslineTenderService.DeleteByID(tempTender.getPt_id());
				mDataItems.remove(tempTender.index);
				mPosSender.send("DELETE "+tempTender.paymentType.getText() + " " +tempTender.getPt_tender());
				mAdapter.notifyDataSetChanged();
				refreshDisplay();
			}
			break;
		}
	}

	/*
	public void printSignaturePaper(PosTender tender) {
		PosPrinter printer = (PosPrinter) DeviceManager.getInstance().printer;
		TransactionManager mTransMgr = TransactionManager.getInstance();
		// new Thread(new Runnable() {
		// public void run() {

//		String signatureContent = "";
//
//		if (printer.getEnable() && !printer.isBusy()) {
//			printer.onConnect();
//			signatureContent = mTransMgr.getCreditContent(tender);
//			printer.print(signatureContent);
//			printer.cutPaper();
//			printer.onDisconnect();
//
//		}
		tender.setNeedPrint(true);
//		mPaymentMgr.SaveEJ(signatureContent);
		// }
		// }).start();

	}*/

}
